"""
Pydantic数据模型（请求/响应模型）
"""
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, EmailStr, validator

# 基础模型
class BaseResponse(BaseModel):
    """基础响应模型"""
    success: bool = True
    message: str = "操作成功"

# 用户相关模型
class UserBase(BaseModel):
    """用户基础信息"""
    username: str
    nickname: Optional[str] = None
    email: EmailStr
    avatar_url: Optional[str] = None

class UserCreate(UserBase):
    """用户创建请求"""
    password: str
    
    @validator('password')
    def password_strength(cls, v):
        if len(v) < 6:
            raise ValueError('密码长度至少6位')
        return v

class UserUpdate(BaseModel):
    """用户更新请求"""
    nickname: Optional[str] = None
    email: Optional[EmailStr] = None
    avatar_url: Optional[str] = None

class UserResponse(UserBase):
    """用户响应模型"""
    id: int
    is_verified: bool
    status: str
    balance: float
    created_at: datetime
    
    class Config:
        from_attributes = True

# 认证相关模型
class Token(BaseModel):
    """令牌响应"""
    access_token: str
    token_type: str = "bearer"
    expires_in: int
    refresh_token: str

class AuthResponse(BaseModel):
    """认证响应"""
    success: bool = True
    message: str = "操作成功"
    data: dict

class LoginRequest(BaseModel):
    """登录请求"""
    username: str
    password: str

class RegisterRequest(UserCreate):
    """注册请求"""
    pass

class RefreshTokenRequest(BaseModel):
    """刷新令牌请求"""
    refresh_token: str


class ChangePasswordRequest(BaseModel):
    """修改密码请求"""
    current_password: str
    new_password: str
    
    @validator('new_password')
    def new_password_strength(cls, v):
        if len(v) < 6:
            raise ValueError('新密码长度至少6位')
        return v

# 商品相关模型
class ProductBase(BaseModel):
    """商品基础信息"""
    title: str
    description: str
    price: float
    category_id: int

    condition: str  # 商品状态：new, like_new, good, fair
    contact_method: Optional[str] = None
    
    @validator('price')
    def price_validator(cls, v):
        if v <= 0:
            raise ValueError('价格必须大于0')
        return v

class ProductCreate(ProductBase):
    """商品创建请求"""
    location: Optional[str] = None
    images: Optional[List[str]] = None

class ProductUpdate(BaseModel):
    """商品更新请求"""
    title: Optional[str] = None
    description: Optional[str] = None
    price: Optional[float] = None
    category_id: Optional[int] = None
    status: Optional[str] = None  # 销售状态：available, reserved, sold

class ProductResponse(ProductBase):
    """商品响应模型"""
    id: int
    user_id: int
    status: str
    view_count: int
    favorite_count: int
    location: Optional[str]
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True

class ProductImageResponse(BaseModel):
    """商品图片响应"""
    id: int
    product_id: int
    image_url: str
    sort_order: int

class ImageUploadResponse(BaseModel):
    """图片上传响应"""
    success: bool = True
    message: str = "上传成功"
    image_url: str

# 分类相关模型
class CategoryResponse(BaseModel):
    """分类响应模型"""
    id: int
    name: str
    parent_id: Optional[int]
    icon_url: Optional[str]
    description: Optional[str]
    sort_order: int
    is_active: bool
    
    class Config:
        from_attributes = True

class CategoryListResponse(BaseModel):
    """分类列表响应模型"""
    status: str = "success"
    data: List[CategoryResponse]

# 交易相关模型
class TradeBase(BaseModel):
    """交易基础信息"""
    product_id: int
    amount: float
    payment_method: Optional[str] = None

class TradeCreate(TradeBase):
    """交易创建请求"""
    remark: Optional[str] = None

class TradeUpdate(BaseModel):
    """交易更新请求"""
    status: Optional[str] = None
    remark: Optional[str] = None

class TradeResponse(TradeBase):
    """交易响应模型"""
    id: int
    trade_no: str
    buyer_id: int
    seller_id: int
    status: str
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True

# 消息相关模型
class MessageBase(BaseModel):
    """消息基础信息"""
    receiver_id: int
    content: str
    message_type: str = "text"

class MessageCreate(MessageBase):
    """消息创建请求"""
    pass

class MessageResponse(MessageBase):
    """消息响应模型"""
    id: int
    sender_id: int
    is_read: bool
    created_at: datetime
    
    class Config:
        from_attributes = True

# 评价相关模型
class EvaluationBase(BaseModel):
    """评价基础信息"""
    trade_id: int
    overall_score: float
    content: Optional[str] = None
    is_anonymous: bool = False

class EvaluationCreate(EvaluationBase):
    """评价创建请求"""
    product_quality_score: Optional[int] = None
    service_attitude_score: Optional[int] = None
    logistics_speed_score: Optional[int] = None

class EvaluationResponse(EvaluationBase):
    """评价响应模型"""
    id: int
    evaluator_id: int
    evaluated_id: int
    evaluation_type: str
    status: str
    created_at: datetime
    
    class Config:
        from_attributes = True

# 评价相关模型（Review）
class ReviewBase(BaseModel):
    """评价基础信息"""
    trade_id: int
    rating: int
    comment: Optional[str] = None

class ReviewCreate(ReviewBase):
    """评价创建请求"""
    pass

class ReviewResponse(ReviewBase):
    """评价响应模型"""
    id: int
    reviewer_id: int
    reviewed_user_id: int
    review_type: str
    created_at: datetime
    
    class Config:
        from_attributes = True

# 钱包相关模型
class WalletResponse(BaseModel):
    """钱包响应模型"""
    user_id: int
    balance: float
    updated_at: datetime

class TransactionResponse(BaseModel):
    """交易记录响应模型"""
    id: int
    wallet_id: int
    transaction_type: str  # deposit, withdrawal, trade_payment, trade_received
    amount: float
    description: Optional[str] = None
    status: str
    created_at: datetime
    
    class Config:
        from_attributes = True

# 分页响应模型
class PaginatedResponse(BaseModel):
    """分页响应模型"""
    items: List
    total: int
    page: int
    size: int
    pages: int